package com.weidong.mybbs.service;

import com.weidong.mybbs.exception.BusinessException;
import com.weidong.mybbs.util.ImageCaptchaUtil;
import com.weidong.mybbs.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.awt.image.BufferedImage;

@Service
public class CaptcheService {

    @Autowired
    private JedisPool jedisPool;

    private static final String IMG_CAPTCHA_REDIS_KEY = "Auth:Img-Captcha:%s";

    /**
     * 生成图片验证码
     * @return
     */
    public BufferedImage getImgCaptcha(String sessionId){
        //生成验证码
        String code = UUIDUtil.randomStr(true,5);
        String key = String.format(IMG_CAPTCHA_REDIS_KEY,sessionId);
        try (Jedis jedis = jedisPool.getResource()){
            jedis.setex(key,300,code.toLowerCase());
        }
        return ImageCaptchaUtil.drawCaptcha(code);
    }

    /**
     * 验证验证码
     * @param sessionId
     * @param code
     * @return
     */
    public boolean validImgCaptcha(String sessionId,String code){
        if (StringUtils.isBlank(sessionId)){
            throw new BusinessException("sessionId有误");
        }
        if (StringUtils.isBlank(code)){
            throw new BusinessException("验证码输入有误");
        }
        String key = String.format(IMG_CAPTCHA_REDIS_KEY,sessionId);
        try (Jedis jedis = jedisPool.getResource()){
            if (jedis.exists(key)){
                return StringUtils.trimToEmpty(jedis.get(key)).toLowerCase().equals(code);
            }

            return false;
        }
    }

}
